﻿using System.Security.Claims;
using K9Nano.Dependency;
using K9Nano.Domain.Caching;
using K9Nano.Session;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace K9Nano.Domain.Session;

public class HttpUserContextAccessor(IHttpContextAccessor httpContextAccessor) : IUserContextAccessor, IScopedDependency
{
    private IUserContext? _current;

    public IUserContext? CurrentUser => _current ??= GetUserContext();

    protected virtual IUserContext? GetUserContext()
    {
        var ctx = httpContextAccessor.HttpContext;
        if (ctx?.User?.Identity?.IsAuthenticated != true)
        {
            return null;
        }
        var sid = ctx.User.Claims.FirstOrDefault(a => a.Type == ClaimTypes.Sid)?.Value;
        if (string.IsNullOrWhiteSpace(sid)) return null;
        if (!long.TryParse(sid, out var userId)) return null;
        var userCache = ctx.RequestServices.GetRequiredService<IUserCache>();
        var user = userCache.GetUser(userId);
        if (user == null) return null;
        return new UserContext
        {
            UserId = userId,
            Username = user.Username,
            Name = user.Name,
            Roles = [.. user.Roles],
            Permissions = [.. user.Permissions],
            OrganizationId= user.OrganizationId,
        };
    }
}